const api = require('../../utils/api');
const { checkLogin, setLoginState } = require('../../utils/auth');

Page({
  data: {
    banner: '',
    categories: [],
    allProducts: [], // 所有商品
    products: [],    // 当前分类商品
    currentCategory: 0,
    cart: [],
    totalAmount: 0,
    showDetail: false,
    detailProduct: {},
    detailQty: 1,
    showCartBar: false, // 是否显示底部购物车栏
    showCartPopup: false, // 是否显示购物车弹窗
    showAuthPopup: false, // 是否显示登录弹窗
    popupUserInfo: null, // 弹窗用户信息
    isLoading: false, // 登录加载状态
  },
  onLoad() {
    this.loadData();
  },
  loadData: async function() {
    try {
      const [categoriesRes, productsRes] = await Promise.all([
        api.getCategories(),
        api.getProducts()
      ]);
      const categories = categoriesRes.categories;
      const allProducts = productsRes.products;
      // 默认显示第一个分类
      const firstCategoryId = categories[0]?.id;
      const products = allProducts.filter(item => item.categoryId === firstCategoryId);
      this.setData({
        categories,
        allProducts,
        products,
        currentCategory: 0
      });
    } catch (error) {
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },
  switchCategory: function(e) {
    const index = e.currentTarget.dataset.index;
    const categoryId = this.data.categories[index].id;
    const products = this.data.allProducts.filter(item => item.categoryId === categoryId);
    this.setData({
      currentCategory: index,
      products
    });
  },
  showProductDetail: function(e) {
    const product = e.currentTarget.dataset.product;
    // 深拷贝，避免弹窗操作影响原数据
    const detailProduct = JSON.parse(JSON.stringify(product));
    this.setData({
      showDetail: true,
      detailProduct,
      detailQty: 1
    });
  },
  hideProductDetail: function() {
    this.setData({ showDetail: false });
  },
  selectOption: function(e) {
    const groupIdx = e.currentTarget.dataset.optgroup;
    const optIdx = e.currentTarget.dataset.optindex;
    const detailProduct = this.data.detailProduct;
    // 单选，先全部取消
    detailProduct.options[groupIdx].choices.forEach((c, idx) => {
      c.selected = (idx == optIdx);
    });
    this.setData({ detailProduct });
  },
  increaseQty: function() {
    this.setData({ detailQty: this.data.detailQty + 1 });
  },
  decreaseQty: function() {
    if (this.data.detailQty > 1) {
      this.setData({ detailQty: this.data.detailQty - 1 });
    }
  },
  addDetailToCart: function() {
    const product = this.data.detailProduct;
    const qty = this.data.detailQty;
    const cart = this.data.cart;
    const index = cart.findIndex(item => item.id === product.id);
    // 强制带上 image 字段
    const image = product.image || (this.data.products.find(p => p.id === product.id) || {}).image || '/images/default-product.png';
    if (index > -1) {
      cart[index].quantity += qty;
      cart[index].image = image;
    } else {
      cart.push({ ...product, quantity: qty, image });
    }
    this.setData({
      cart,
      totalAmount: this.calculateTotal(cart),
      showDetail: false,
      showCartBar: true
    });
    wx.showToast({ title: '已加入购物车', icon: 'success' });
  },
  addToCart: function(e) {
    const product = e.currentTarget.dataset.product;
    const cart = this.data.cart;
    const index = cart.findIndex(item => item.id === product.id);
    
    if (index > -1) {
      cart[index].quantity += 1;
    } else {
      cart.push({
        ...product,
        quantity: 1
      });
    }
    
    this.setData({ 
      cart,
      totalAmount: this.calculateTotal(cart)
    });
  },
  calculateTotal: function(cart) {
    return cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
  },
  submitOrder: async function() {
    if (this.data.cart.length === 0) {
      wx.showToast({
        title: '请先选择商品',
        icon: 'none'
      });
      return;
    }

    try {
      const orderData = {
        items: this.data.cart,
        totalAmount: this.data.totalAmount
      };
      
      await api.createOrder(orderData);
      
      wx.showToast({
        title: '下单成功',
        icon: 'success'
      });
      
      this.setData({ 
        cart: [],
        totalAmount: 0
      });
      
      wx.switchTab({
        url: '/pages/orders/orders'
      });
    } catch (error) {
      wx.showToast({
        title: '下单失败',
        icon: 'error'
      });
    }
  },
  // 点击购物车栏显示购物车弹窗
  showCartPopup: function() {
    this.setData({ showCartPopup: true });
  },
  // 关闭购物车弹窗
  closeCartPopup: function() {
    this.setData({ showCartPopup: false });
  },
  // 购物车弹窗内加减数量
  cartIncreaseQty: function(e) {
    const index = e.currentTarget.dataset.index;
    const cart = this.data.cart;
    cart[index].quantity += 1;
    this.setData({
      cart,
      totalAmount: this.calculateTotal(cart)
    });
  },
  cartDecreaseQty: function(e) {
    const index = e.currentTarget.dataset.index;
    const cart = this.data.cart;
    if (cart[index].quantity > 1) {
      cart[index].quantity -= 1;
      this.setData({
        cart,
        totalAmount: this.calculateTotal(cart)
      });
    }
  },
  // 检查登录状态
  checkLogin: function() {
    if (checkLogin()) {
      return true;
    }
    // 显示登录弹窗
    const userInfo = wx.getStorageSync('userInfo') || null;
    this.setData({ showAuthPopup: true, popupUserInfo: userInfo });
    return false;
  },
  // 关闭登录弹窗
  closeAuthPopup: function() {
    this.setData({ showAuthPopup: false });
    this.pendingAction = null;
  },
  // 处理登录授权
  handleAuthLogin: function() {
    if (this.data.isLoading) return;
    this.setData({ isLoading: true });
    wx.getUserProfile({
      desc: '用于完善会员资料',
      lang: 'zh_CN',
      success: async (userProfile) => {
        try {
          const loginRes = await wx.login();
          if (!loginRes.code) throw new Error('获取登录码失败');
          const res = await api.login({
            code: loginRes.code,
            userInfo: userProfile.userInfo
          });
          if (!setLoginState(res)) throw new Error('保存登录状态失败');
          this.setData({
            showAuthPopup: false,
            popupUserInfo: res.userInfo
          });
          wx.showToast({ title: '登录成功', icon: 'success', duration: 1500 });
          // 登录成功后继续之前的操作
          if (this.pendingAction) {
            this.pendingAction();
            this.pendingAction = null;
          }
        } catch (e) {
          wx.showToast({ title: e.errMsg || '登录失败', icon: 'error', duration: 2000 });
        } finally {
          this.setData({ isLoading: false });
        }
      },
      fail: () => {
        wx.showToast({ title: '用户拒绝授权', icon: 'none' });
        this.setData({ isLoading: false, showAuthPopup: false });
      }
    });
  },
  // 立即购买
  buyNow: function() {
    console.log('buyNow');
    const isLoggedIn = this.checkLogin();
    console.log('checkLogin result:', isLoggedIn);
    console.log('showAuthPopup:', this.data.showAuthPopup);
    if (!isLoggedIn) {
      this.pendingAction = () => this.buyNow();
      return;
    }
    const product = this.data.detailProduct;
    const qty = this.data.detailQty;
    if (!product || !qty) return;

    // 生成订单并写入本地
    const orders = wx.getStorageSync('orders') || [];
    const newOrder = {
      id: Date.now(),
      items: [{ ...product, quantity: qty }],
      totalAmount: product.price * qty,
      status: 1,
      createTime: new Date().toLocaleString()
    };
    orders.unshift(newOrder);
    wx.setStorageSync('orders', orders);

    wx.showToast({ title: '下单成功', icon: 'success' });
    this.setData({ showDetail: false });

    // 跳转到订单列表页
    wx.switchTab({
      url: '/pages/orders/orders'
    });
  },
  // 购物车结算
  cartCheckout: function() {
    if (!this.checkLogin()) {
      this.pendingAction = this.cartCheckout;
      return;
    }
    
    if (this.data.cart.length === 0) {
      wx.showToast({ title: '购物车为空', icon: 'none' });
      return;
    }

    // 跳转到订单确认页
    const orderData = {
      items: this.data.cart,
      totalAmount: this.data.totalAmount
    };
    
    wx.navigateTo({
      url: '/pages/order-confirm/order-confirm?orderData=' + JSON.stringify(orderData)
    });
  },
  // 购物车清空
  clearCart: function() {
    this.setData({ cart: [], totalAmount: 0, showCartBar: false, showCartPopup: false });
    wx.showToast({ title: '购物车已清空', icon: 'success' });
  },
}); 